<template>
  <div class="file-manager-container">
    <!-- 左侧树形导航 -->
    <div class="sidebar">
      <div class="tree-header">
        <span>文件夹结构</span>
        <el-button
          type="info"
          size="small"
          circle
          @click="refreshFolderTreeMain"
          :icon="Refresh"
        />
      </div>
      <el-tree
        ref="folderTreeMainRef"
        :data="fileTree"
        :props="treeProps"
        node-key="id"
        :expand-on-click-node="false"
        :highlight-current="true"
        @node-click="handleFolderClick"
      >
        <template #default="{ node, data }">
          <span class="tree-node">
            <el-icon><Folder /></el-icon>
            <span class="node-label">{{ node.label }}</span>
            <span class="node-actions">
              <el-button
                type="primary"
                link
                :icon="Plus"
                @click.stop="showCreateSubFolderDialog(data)"
              />
            </span>
          </span>
        </template>
      </el-tree>
    </div>

    <!-- 右侧内容区 -->
    <div class="main-content">
      <el-header>
        <div class="header-left">
          <h2>学院数据管理系统</h2>
        </div>
        <div class="header-right">
          <el-dropdown @command="handleCommand">
            <span class="user-dropdown">
              {{ username }}
              <el-icon><ArrowDown /></el-icon>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="logout">退出登录</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </el-header>

      <!-- 面包屑导航 -->
      <div class="breadcrumb-bar">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item
            v-for="(item, index) in currentPath"
            :key="index"
            @click="updateBreadcrumb(item)"
          >
            {{ item.name }}
          </el-breadcrumb-item>
        </el-breadcrumb>
      </div>

      <div class="operation-buttons">
        <el-button type="primary" @click="openUploadDialog">
          <el-icon><Upload /></el-icon>
          上传
        </el-button>
        <el-button type="primary" :icon="Share" @click="showExportDialog">
          导出
        </el-button>
        <!-- <el-button @click="createNewFolder">
          <el-icon><FolderAdd /></el-icon>
          新建文件夹
        </el-button> -->
      </div>
      <!-- 文件列表 -->
      <section class="file-list">
        <!-- 文件操作栏 -->
        <div class="file-operations">
          <!-- <el-checkbox v-model="selectAll">全选</el-checkbox>
           <el-dropdown>
            <el-button type="primary">
              批量操作<el-icon class="el-icon--right"><arrow-down /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item>导出</el-dropdown-item>
                <el-dropdown-item>移动</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown> -->
        </div>

        <!-- 文件列表 -->
        <div class="file-grid">
          <div
            v-for="file in currentFileList"
            :key="file.id"
            class="file-item"
            @dblclick="handleFileDblClick(file)"
            @contextmenu.prevent="showContextMenu($event, file)"
            draggable="true"
            @dragstart="handleDragStart(file)"
            @dragend="handleDragEnd"
            @dragover.prevent="handleDragOver($event, file)"
            @drop.prevent="handleDrop($event, file)"
          >
            <el-tooltip placement="bottom">
              <template #content>
                <!-- 太丑了，展示数据还没写格式化 -->
                {{ file.id }}<br />{{ file.descriptions }}
              </template>
              <div>
                <div class="file-icon">
                  <el-icon v-if="file.isFolder"><Folder /></el-icon>
                  <el-icon v-else><Document /></el-icon>
                </div>
                <div class="file-name">{{ file.name }}</div>
                <!-- <div class="file-info">
                  <span>{{ file.id }}</span>
                  <span>{{ file.descriptions }}</span>
                </div> -->
              </div>
            </el-tooltip>
          </div>
        </div>
      </section>
    </div>

    <!-- 右键菜单 -->
    <div
      v-show="contextMenu.visible"
      class="context-menu"
      :style="{ left: contextMenu.x + 'px', top: contextMenu.y + 'px' }"
    >
      <div class="menu-item" @click="handleRename">重命名</div>
      <div class="menu-item" @click="showEditDescDialog">修改描述</div>
      <div class="menu-item" @click="handleDownload">下载</div>
      <div class="menu-item" @click="handleCopy">复制</div>
      <div class="menu-item" @click="handlePaste">粘贴</div>
      <div v-if="isAdmin" class="menu-item danger" @click="handleDelete">
        删除
      </div>
    </div>

    <!-- 修改描述对话框 -->
    <el-dialog v-model="descDialogVisible" title="修改描述">
      <el-form :model="currentFile.desc">
        <el-form-item
          v-for="field in editableFields"
          :key="field.value"
          :label="field.label"
        >
          <el-input v-model="currentFile.desc[field.value]" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="descDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveDescription">保存</el-button>
      </template>
    </el-dialog>

    <!-- 导出对话框 -->
    <el-dialog
      v-model="exportDialogVisible"
      title="导出文件"
      width="1200px"
      :close-on-click-modal="false"
    >
      <div class="export-container">
        <!-- 左侧目录树 -->
        <div class="directory-tree">
          <el-tree
            ref="folderTreeSelect"
            :data="fileTree"
            :props="treeProps"
            node-key="path"
            highlight-current
            @node-click="handleDirectoryClick"
          />
        </div>

        <!-- 右侧文件选择区 -->
        <div class="file-selection">
          <!-- 新增字段选择器 -->
          <div class="field-selector">
            <el-checkbox-group v-model="selectedFields">
              <el-checkbox
                v-for="field in exportFields"
                :key="field.value"
                :label="field.value"
              >
                {{ field.label }}
              </el-checkbox>
            </el-checkbox-group>
          </div>

          <el-table
            :data="filteredFileList"
            style="width: 100%"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column prop="name" label="文件名" />
            <el-table-column label="文件描述">
              <template #default="{ row }">
                <div class="file-description">
                  <div v-for="field in exportFields" :key="field.value">
                    <template v-if="selectedFields.includes(field.value)">
                      <span class="label">{{ field.label }}：</span>
                      <span class="value">{{
                        row.descriptions[field.value] || "未填写"
                      }}</span>
                    </template>
                  </div>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="exportDialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            :loading="exportLoading"
            @click="handleExport"
          >
            导出选中文件（{{ selectedFiles.length }}个）
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 上传文件对话框 -->
    <el-dialog v-model="uploadDialogVisible" title="上传文件">
      <!-- ref="uploadFormRef" -->
      <!-- 文件 -->
      <el-upload
        class="upload-demo"
        :action="uploadUrl"
        :headers="uploadHeaders"
        :before-upload="beforeUpload"
        :on-success="handleUploadSuccess"
        :on-error="handleUploadError"
        :auto-upload="false"
        :on-change="handlefileChangeOne"
        drag
        multiple
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip">
            支持的文件类型：图片、PDF、Word、Excel，单个文件不超过100MB
          </div>
        </template>
      </el-upload>
      <el-form :model="uploadForm" label-width="120px">
        <!-- 名称 -->
        <el-form-item label="名称" required>
          <el-input v-model="uploadForm.name" placeholder="名称"></el-input>
        </el-form-item>
        <!-- 时间 -->
        <el-form-item label="时间" required>
          <el-date-picker
            v-model="uploadForm.awardTime"
            type="datetime"
            placeholder="选择时间"
            :default-value="new Date()"
          ></el-date-picker>
        </el-form-item>
        <!-- 地点 -->
        <el-form-item label="地点">
          <el-input
            v-model="uploadForm.location"
            placeholder="请输入地点"
          ></el-input>
        </el-form-item>
        <!-- 成果类型 -->
        <el-form-item label="成果类型" required>
          <el-select
            v-model="uploadForm.resultType"
            placeholder="请选择成果类型"
          >
            <el-option label="比赛获奖" value="比赛获奖"></el-option>
            <el-option label="论文" value="论文"></el-option>
            <el-option label="党建" value="党建"></el-option>
            <el-option label="外出交流" value="外出交流"></el-option>
            <el-option label="其他" value="其他"></el-option>
          </el-select>
        </el-form-item>
        <!-- 题目 -->
        <el-form-item label="题目" required>
          <el-input
            v-model="uploadForm.title"
            placeholder="请输入题目"
          ></el-input>
        </el-form-item>
        <!-- 负责人 -->
        <el-form-item label="负责人" required>
          <el-input
            v-model="uploadForm.leader"
            placeholder="请输入负责人"
          ></el-input>
        </el-form-item>
        <!-- 参与人员 -->
        <el-form-item label="参与人员">
          <el-input
            v-model="uploadForm.participants"
            placeholder="请输入参与人员"
          ></el-input>
        </el-form-item>
        <!-- 级别 -->
        <el-form-item label="级别">
          <el-input
            v-model="uploadForm.level"
            placeholder="请输入级别"
          ></el-input>
        </el-form-item>
      </el-form>

      <span class="dialog-footer">
        <el-button @click="uploadDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleUpload">确定</el-button>
      </span>
    </el-dialog>

    <!-- 新建文件夹对话框 -->
    <el-dialog v-model="folderDialogVisible" title="新建文件夹">
      <el-form :model="newFolderForm">
        <el-form-item label="文件夹名称">
          <el-input v-model="newFolderForm.name" autocomplete="off" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="folderDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="createFolder">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>
  
  <script setup>
import { ref, reactive, onMounted, computed } from "vue";
import { useRoute, useRouter } from "vue-router";
import {
  HomeFilled,
  Upload,
  FolderAdd,
  Folder,
  Document,
  ArrowDown,
  Share,
  Refresh,
  Plus,
  UploadFilled,
} from "@element-plus/icons-vue";
import axios from "axios";
//import { uploadFile } from "@/api/file.js";
import { ElUpload, ElMessage } from "element-plus";
import { useClipboard } from "@vueuse/core";
import * as XLSX from "xlsx";
import { useUserStore } from "@/stores/user";
import { loadFolderTreeApi,getcurrentFileList,uploadFile } from '@/api/fileApi.js'
const userStore = useUserStore();
const route = useRoute();
const router = useRouter();

const username = ref("用户"); // 这里可以从store或其他地方获取用户名

const handleCommand = (command) => {
  if (command === "logout") {
    localStorage.removeItem("token");
    localStorage.removeItem("userRole");
    router.push("/login");
  }
};

const fileTree = ref([
  {
    id: 1,
    name: "根目录",
    path: "/",
    children: [
      {
        id: 2,
        name: "教学资料",
        path: "/teacher",
        children: [
          { id: 3, name: "2023级",path: "/teaching/2023" },
          { id: 4, name: "2022级",path: "/teaching/2022"},
        ],
      },
      {
        id: 5,
        name: "科研文档",
        path: "/research",
        children: [
          { id: 6, name: "项目报告" , path: "/research/reports"},
          { id: 7, name: "实验数据" , path: "/research/data" },
        ],
      },
    ],
  },
]);
const currentFileList = ref([
    {
        id: 1,
        name: "JAVA程序设计基础.pdf",
        isFolder: false,
        path: "/teaching/2023",
    	descriptions: {
      		name: "JAVA课程讲义",
      		time: "2023-09-01",
      		location: "广东海洋大学",
      		resultType: "教学材料",
      		title: "Java编程基础",
      		leader: "张老师",
      		participants: "李同学, 王同学",
      		level: "校级",
    	},
    },
    {
    id: 2,
    name: "Python实验数据.xlsx",
    isFolder: false,
    path: "/research/data",
    descriptions: {
      name: "Python数据分析",
      time: "2023-09-02",
      location: "实验室",
      resultType: "实验数据",
      title: "数据分析报告",
      leader: "王教授",
      participants: "研究小组",
      level: "省级",
    },
  },
    {
    id: 3,
    name: "我的文档",
    isFolder: true,
    path: "/research/Mydata",
    descriptions: {
    },
  },
])

// 响应式状态
//const folderTreeMain = ref([]);
const currentPath = ref([{ id: 1, name: "根目录" }]);
const folderDialogVisible = ref(false);
const newFolderForm = ref({ name: "", parentId: null });
const treeProps = {
  label: "name",
  children: "children",
};

// 初始化加载文件夹树
const loadFolderTree = async () => {
  try {
    // 调用API
    const res = await loadFolderTreeApi()
    fileTree.value = res.data
  } catch (error) {
    console.error("加载文件夹树失败:", error);
  }
};

// 创建子文件夹
const createFolder = async () => {
  if (!newFolderForm.value.name.trim()) {
    alert("请输入文件夹名称");
    return;
  }

  const nFolder = {
    name: newFolderForm.value.name,
    parentId: newFolderForm.value.parentId
  };

  try {
    // 调用api,返回新建的文件夹（id,name,path,children: []）
    const res = await createFolderApi(nFolder)
    // await axios.post('/api/folders', {
    //   name: newFolderForm.value.name,
    //   parentId: newFolderForm.value.parentId
    // })

    // 创建结果
    const newFolder = res.data

    // 更新树形结构
    const parentNode = findNodeById(
      fileTree.value,
      newFolderForm.value.parentId
    );
    if (parentNode) {
      if (!parentNode.children) parentNode.children = [];
      parentNode.children.push(newFolder);
    }

    folderDialogVisible.value = false;
    newFolderForm.value.name = "";
  } catch (error) {
    console.error("创建文件夹失败:", error);
  }
};

// 查找树节点
const findNodeById = (nodes, id) => {
  for (const node of nodes) {
    if (node.id === id) return node;
    if (node.children) {
      const found = findNodeById(node.children, id);
      if (found) return found;
    }
  }
  return null;
};

// 显示创建对话框
const showCreateSubFolderDialog = (parentData) => {
  newFolderForm.value.parentId = parentData.id;
  folderDialogVisible.value = true;
};

// 刷新树形结构
const refreshFolderTreeMain = () => {
  loadFolderTree();
};

// 处理文件夹点击
const handleFolderClick = (data) => {
  updateBreadcrumb(data);
  //console.log(data.name)
};

// TODO 更新面包屑导航
const updateBreadcrumb = (node) => {
  const path = [];
  let current = findNodeById(fileTree.value, node.id);
  while (current) {
    path.unshift(current);
    current = findNodeById(fileTree.value, current.parentId);
  }
  currentPath.value = path;
  //console.log(currentPath.value);
};


// 双击文件时的处理函数
const handleFileDblClick = (file) => {
  if (file.isFolder) {
    // 处理双击文件夹的逻辑，例如进入文件夹
    //const newPath = currentPath.value + "\\" + file.name;
    currentPath.value.push({id: file.id,name: file.name}) ;
    currentFileList.value = [];
    console.log(currentPath.value);
    fetchFilesByPath(currentPath.value);
  } else {
    // 处理双击文件的逻辑，例如打开文件
    console.log(`打开文件: ${file.name}`);
  }
};

// 上传对话框是否可见
const uploadDialogVisible = ref(false);
// 修改上传配置，使用计算属性
const uploadUrl = `${import.meta.env.VITE_API_BASE_URL}/api/file/upload`;
const uploadHeaders = computed(() => ({
  Authorization: `Bearer ${userStore.token}`,
}));
// 上传表单数据
const uploadForm = ref({
  path: "",
  name: "",
  awardTime: new Date(),
  location: "",
  resultType: "",
  title: "",
  leader: "",
  participants: "",
  level: "",
});
// 上传表单引用
const uploadFormRef = ref();
const uploadSelectedFile = ref([]);
// 打开上传对话框
const openUploadDialog = () => {
  console.log("openUploadDialog 方法被调用");
  uploadDialogVisible.value = true;
};

const beforeUpload = (file) => {
  const maxSize = 100 * 1024 * 1024; // 100MB
  if (file.size > maxSize) {
    ElMessage.error("文件大小不能超过100MB");
    return false;
  }
  uploadSelectedFile.value.push(file);
  //console.log('nh');
  //console.log(uploadSelectedFile.value);
  return false; //阻止自动上传
};
const handlefileChangeOne = (file) => {
  const maxSize = 100 * 1024 * 1024; // 100MB
  if (file.size > maxSize) {
    ElMessage.error("文件大小不能超过100MB");
    return false;
  }
  uploadSelectedFile.value.push(file);
  //console.log(uploadSelectedFile.value);
};
const handleUploadSuccess = (response) => {
  ElMessage.success("上传成功");
  uploadDialogVisible.value = false;
};

const handleUploadError = () => {
  ElMessage.error("上传失败");
};

// 处理上传操作
const handleUpload = async () => {
  try {
    // 创建 FormData 对象
    const formData = new FormData();

    // 添加表单数据
    for (const key in uploadForm.value) {
      formData.append(key, uploadForm.value[key]);
    }

    formData.append("files", uploadSelectedFile);
    // 添加文件数据
    /* uploadSelectedFile.value.forEach((file) => {
      formData.append("files", file);
    }); */
    // 发送请求
    /* const response = await axios.post(uploadUrl, formData, {
      headers: {
        ...uploadHeaders.value,
        "Content-Type": "multipart/form-data",
      },
    }); */
    for (var [key, value] of formData) {
      console.log(key, value);
    }
    const response = await uploadFile(formData);
    console.log("上传成功", response.data);
    // 关闭对话框
    uploadDialogVisible.value = false;
    // 清空表单和文件信息
    uploadForm.value = {
      name: "",
      awardTime: null,
      location: "",
      resultType: "",
      title: "",
      leader: "",
      participants: "",
      level: "",
    };
    uploadSelectedFile.value = [];
  } catch (error) {
    console.error("上传失败", error);
  }
};

// 根据路径获取文件列表和描述的函数
const fetchFilesByPath = async (path) => {
  //api请求返回当前路径的文件列表数据
  const res = await getcurrentFileList()
  currentFileList.value = res.data
};

// 导出相关状态
const exportDialogVisible = ref(false);
const exportLoading = ref(false);
const selectedFiles = ref([]);

// 新增过滤方法
/* const filteredDescriptions = (descriptions) => {
  return Object.entries(descriptions).filter(([key]) => 
    Object.keys(descriptionLabels).includes(key)
  ).reduce((obj, [key, val]) => {
    obj[key] = val
    return obj
  }, {})
} */

// 确保字段映射正确
const descriptionLabels = reactive({
  name: "名称",
  time: "时间",
  location: "地点",
  resultType: "成果类型",
  title: "题目",
  leader: "负责人",
  participants: "参与人员",
  level: "级别",
});
// 新增状态
const exportFields = ref([
  { label: "名称", value: "name" },
  { label: "时间", value: "time" },
  { label: "地点", value: "location" },
  { label: "成果类型", value: "resultType" },
  { label: "题目", value: "title" },
  { label: "负责人", value: "leader" },
  { label: "参与人员", value: "participants" },
  { label: "级别", value: "level" },
]);
const selectedFields = ref(exportFields.value.map((f) => f.value)); // 默认全选
// 树形配置
/* const treeProps = {
  label: 'name',
  children: 'children'
} */
const filteredFileList = computed(() => {
  return currentFileList.value.filter(file => !file.isFolder)
})
// 显示导出对话框
const showExportDialog = async () => {
  exportDialogVisible.value = true;

  // 这里应调用API加载目录结构selectedFiles.value = [];
  // await loadDirectoryStructure()
};

// 处理目录点击
const handleDirectoryClick = async (node) => {
  console.log("Clicked directory node:", node);
  // 调用API获取当前路径文件列表
  // const res = await axios.get(`/api/files?path=${node.path}`)
  // currentFileList.value = res.data
};

// 处理选择变化
const handleSelectionChange = (selection) => {
  console.log("Selected files:", selection);
  selectedFiles.value = selection;
};

// 执行导出
const handleExport = async () => {
  console.log("Exporting selected files:", selectedFiles.value);
  if (selectedFiles.value.length === 0) {
    ElMessage.warning("请至少选择一个文件");
    return;
  }

  if (selectedFields.value.length === 0) {
    ElMessage.warning("请至少选择一个导出字段");
    return;
  }

  exportLoading.value = true;
  try {
    const exportData = selectedFiles.value.map((file) => {
      const baseInfo = {
        文件名: file.name,
        //'文件路径': file.path
      };

      const descriptions = selectedFields.value.reduce((obj, field) => {
        const label = exportFields.value.find((f) => f.value === field)?.label;
        obj[label || field] = file.descriptions[field] || "";
        return obj;
      }, {});

      return { ...baseInfo, ...descriptions };
    });

    // 生成Excel
    const workbook = XLSX.utils.book_new();
    const worksheet = XLSX.utils.json_to_sheet(exportData);
    XLSX.utils.book_append_sheet(workbook, worksheet, "文件描述");

    // 下载文件
    const wbout = XLSX.write(workbook, { type: "array", bookType: "xlsx" });
    const blob = new Blob([wbout], { type: "application/octet-stream" });
    const url = URL.createObjectURL(blob);
    const link = document.createElement("a");
    link.href = url;
    link.download = `文件导出_${new Date().toISOString().slice(0, 10)}.xlsx`;
    link.click();

    ElMessage.success(`成功导出${selectedFiles.value.length}个文件`);
    exportDialogVisible.value = false;
  } catch (error) {
    ElMessage.error("导出失败: " + error.message);
  } finally {
    exportLoading.value = false;
  }
};

// 用户权限状态
const isAdmin = ref(true);
// 剪贴板功能
const { copy, copied } = useClipboard();
// 右键菜单状态
const contextMenu = reactive({
  visible: false,
  x: 0,
  y: 0,
  targetFile: null,
});
// 拖拽状态
const dragState = reactive({
  isDragging: false,
  sourceFile: null,
});
// 文件描述编辑
const descDialogVisible = ref(false);
const currentFile = reactive({
  data: null,
  desc: {},
});

// 可编辑字段配置
const editableFields = [
  { label: "名称", value: "name" },
  { label: "时间", value: "time" },
  { label: "地点", value: "location" },
  { label: "成果类型", value: "resultType" },
  { label: "题目", value: "title" },
  { label: "负责人", value: "leader" },
  { label: "参与人员", value: "participants" },
  { label: "级别", value: "level" },
];

// 显示右键菜单
const showContextMenu = (event, file) => {
  contextMenu.visible = true;
  contextMenu.x = event.clientX;
  contextMenu.y = event.clientY;
  contextMenu.targetFile = file;
  const menuWidth = 160; // 根据实际菜单宽度调整
  if (contextMenu.x + menuWidth > window.innerWidth) {
    contextMenu.x = window.innerWidth - menuWidth;
  }

  // 防止菜单超出视口底部
  const menuHeight = 200; // 根据实际菜单高度调整
  if (contextMenu.y + menuHeight > window.innerHeight) {
    contextMenu.y = window.innerHeight - menuHeight;
  }

  document.addEventListener("click", closeContextMenu);
};

// 关闭右键菜单
const closeContextMenu = () => {
  contextMenu.visible = false;
  document.removeEventListener("click", closeContextMenu);
};

// 文件操作处理函数
const handleRename = async () => {
  const newName = prompt("请输入新文件名", contextMenu.targetFile.name);
  if (newName) {
    try {
      //TODO await axios.patch(`/files/${contextMenu.targetFile.id}`, { name: newName })
      contextMenu.targetFile.name = newName;
      ElMessage.success("重命名成功");
    } catch (error) {
      ElMessage.error("重命名失败");
    }
  }
  closeContextMenu();
};

const showEditDescDialog = () => {
  currentFile.data = contextMenu.targetFile;
  currentFile.desc = { ...contextMenu.targetFile.descriptions };
  descDialogVisible.value = true;
  closeContextMenu();
};

const saveDescription = async () => {
  try {
    //TODO await axios.patch(`/files/${currentFile.data.id}/desc`, currentFile.desc)
    currentFile.data.descriptions = { ...currentFile.desc };
    ElMessage.success("描述修改成功");
    descDialogVisible.value = false;
  } catch (error) {
    ElMessage.error("修改失败");
  }
};

const handleDownload = () => {
  // 下载逻辑
  ElMessage.info("开始下载：" + contextMenu.targetFile.name);
  closeContextMenu();
};

const handleCopy = () => {
  //TODO
  copy(JSON.stringify(contextMenu.targetFile));
  ElMessage.success("已复制文件信息");
  closeContextMenu();
};

const handlePaste = async () => {
  try {
    //TODO
    // const fileData = await navigator.clipboard.readText()
    // const newFile = JSON.parse(fileData)
    // await axios.post('/files', newFile)
    ElMessage.success("粘贴成功");
  } catch (error) {
    ElMessage.error("粘贴失败");
  }
  closeContextMenu();
};

const handleDelete = async () => {
  if (confirm(`确定删除 ${contextMenu.targetFile.name} 吗？`)) {
    try {
      // TODO await axios.delete(`/files/${contextMenu.targetFile.id}`)
      currentFileList.value = currentFileList.value.filter(
        (f) => f.id !== contextMenu.targetFile.id
      );
      ElMessage.success("删除成功");
    } catch (error) {
      ElMessage.error("删除失败");
    }
  }
  closeContextMenu();
};

// 拖拽处理
const handleDragStart = (file) => {
  dragState.isDragging = true;
  dragState.sourceFile = file;
  event.dataTransfer.effectAllowed = "move";
};

const handleDragEnd = () => {
  dragState.isDragging = false;
  dragState.sourceFile = null;
};

const handleDragOver = (event, targetFile) => {
  if (targetFile.isFolder) {
    event.dataTransfer.dropEffect = "move";
  }
};

const handleDrop = async (event, targetFile) => {
  if (!targetFile.isFolder) return;

  try {
    // TODO await axios.patch(`/files/${dragState.sourceFile.id}`, {
    //   parentId: targetFile.id
    // })
    ElMessage.success(`已移动到 ${targetFile.name}`);
  } catch (error) {
    ElMessage.error("移动失败");
  }
};

// 初始化加载
onMounted(() => {
  loadFolderTree();
  fetchFilesByPath(currentPath);
});
</script>
  
  <style scoped>
.file-manager-container {
  display: flex;
  height: 100vh;
  background: #f5f7fa;
}

.sidebar {
  width: 280px;
  background: white;
  border-right: 1px solid #ebeef5;
  padding: 20px;
  overflow-y: auto;
}

.main-content {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
}

.tree-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  font-size: 16px;
  color: #303133;
}

.tree-node {
  display: flex;
  align-items: center;
  width: 100%;
  padding: 5px 0;
}

.node-label {
  margin-left: 8px;
  flex: 1;
}

.node-actions {
  visibility: hidden;
  margin-left: auto;
}

.el-tree-node__content:hover .node-actions {
  visibility: visible;
}

.breadcrumb-bar {
  background: white;
  padding: 15px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.sidebar {
  width: 200px;
  border-right: 1px solid #eee;
  padding: 16px;
}

.menu-item {
  padding: 12px;
  display: flex;
  align-items: center;
  cursor: pointer;
}

.menu-item:hover {
  background: #f5f5f5;
}

.menu-item .el-icon {
  margin-right: 8px;
}

.file-list {
  flex: 1;
  padding: 16px;
  overflow: auto;
}

.file-operations {
  display: flex;
  justify-content: space-between;
  margin-bottom: 16px;
}

.file-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
  gap: 20px;
}

.file-item {
  text-align: center;
  padding: 10px;
  border-radius: 4px;
  cursor: pointer;
}

.file-item:hover {
  background: #f5f5f5;
}

.file-icon .el-icon {
  font-size: 48px;
  color: #409eff;
}

.file-name {
  margin-top: 8px;
  word-break: break-all;
}

.file-info {
  margin-top: 4px;
  font-size: 12px;
  color: #999;
  display: flex;
  flex-direction: column;
}

.upload-demo {
  text-align: center;
}

.export-container {
  display: flex;
  height: 60vh;
}

.directory-tree {
  width: 250px;
  border-right: 1px solid #ebeef5;
  padding-right: 20px;
  overflow-y: auto;
}

.file-selection {
  flex: 1;
  padding-left: 20px;
  overflow-y: auto;
}

.file-description {
  padding: 8px;
  font-size: 12px;
  line-height: 1.5;
}

.file-description .label {
  color: #909399;
  min-width: 60px;
  display: inline-block;
}

.file-description .value {
  color: #606266;
}

.dialog-footer {
  padding-top: 20px;
  text-align: right;
}
:deep(.el-tree-node__content) {
  height: 40px;
}
.field-selector {
  margin-bottom: 20px;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.el-checkbox-group {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
}

.el-checkbox {
  margin-right: 0;
}
.context-menu {
  position: fixed;
  background: white;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  border-radius: 4px;
  z-index: 9999;
  min-width: 160px;
  /* 移除可能影响定位的transform */
  transform: none;
  /* 确保没有外边距影响定位 */
  margin: 0;
}

.user-dropdown {
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 4px;
}
.el-header {
  background-color: #fff;
  border-bottom: 1px solid #dcdfe6;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 10px;
  margin: 5px 0;
}
</style>